﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Windows.Forms;
using System.IO;
using System.Threading;

namespace HousingDistribution
{
    public partial class FormHousingDis : Form
    {
        public FormHousingDis()
        {
            InitializeComponent();

            //处理界面布局
            this.dataGridView.Dock = DockStyle.Fill;
            this.dataGridView.Anchor = ((AnchorStyles)
                                        ((((AnchorStyles.Top
                                          | AnchorStyles.Bottom)
                                          | AnchorStyles.Left)
                                          | AnchorStyles.Right)));

            this.panelProgressBar.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
            this.groupBoxPersonType.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
            this.radioBtnPerArmyMan.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
            this.radioBtnPerStaff.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
            this.radioBtnPerWorker.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
            this.radioBtnPerSeniorNCO.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;

            this.buttonBeforeTimePeople.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
            this.BtnBothEmployeeScreening.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
            this.BtnProc.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
            this.BtnReport.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
            this.BtnClose.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;

            this.FormBorderStyle = FormBorderStyle.None;
            
            InitDGV();

            //报表按钮默认是不能操作的
            this.BtnReport.Enabled = false;
        }
        
        private void FormHousingDis_Load(object sender, EventArgs e)
        {
            this.Dock = DockStyle.Fill;

            MessageBox.Show("当前系统默认的分房时间是：" + HousingDisDeadline.Instance().Deadline().ToShortDateString());
        }

        #region 读取数据
        PersonTypeEnum GetPersonType()
        {
            if (radioBtnPerArmyMan.Checked)
                return PersonTypeEnum.ArmMan;
            else if (radioBtnPerStaff.Checked)
                return PersonTypeEnum.Staff;
            else if (radioBtnPerSeniorNCO.Checked)
                return PersonTypeEnum.NCO;
            else if (radioBtnPerWorker.Checked)
                return PersonTypeEnum.Worker;
            else
                return PersonTypeEnum.Unknown;
        }

        void ReadData(PersonTypeEnum type)
        {
            this.dataGridView.DataSource = null;

            DGVDisplay(personType, false);

            ReadDataProxy reader = new ReadDataProxy(this.personType, this.BindData);
            Thread readThread = new Thread(reader.Read);
            readThread.Start();
        }

        class ReadDataProxy
        {
            public ReadDataProxy(PersonTypeEnum personType, BindDataDelegate bindDataFunc)
            {
                this.personType = personType;
                this.bindDataFunc = bindDataFunc;
            }

            public void Read()
            {
                if (personType == PersonTypeEnum.ArmMan || personType == PersonTypeEnum.NCO
                    || personType == PersonTypeEnum.Staff || personType == PersonTypeEnum.Worker)
                {
                    string sqlReadData = "select * from person where type ='"
                                            + ((int)personType).ToString() + "'";

                    DataTable dt = null;

                    try
                    {
                        dt = DBProc.Instance().ReadData(sqlReadData).Tables[0];

                        for (int i = 0; i < dt.Rows.Count; i++ )
                        {
                            DataRow dr = dt.Rows[i];
                            DataTableInvalidDateCell2Null.Format(ref dr, timeTypeCols);
                        }
                    }
                    catch (Exception e)
                    {
                        System.Windows.Forms.MessageBox.Show(e.Message);
                    }

                    bindDataFunc(dt);
                }
            }

            BindDataDelegate bindDataFunc;
            PersonTypeEnum personType;
        }
        
        #endregion

        #region 界面操作响应处理
        private void BtnBothEmployeeScreening_Click(object sender, EventArgs e)
        {
            FormBothEmpScreening form = new FormBothEmpScreening();
            form.ShowDialog();
        }

        private void BtnProc_Click(object sender, EventArgs e)
        {
            FormRptPara formRptPara = new FormRptPara();
            formRptPara.SetGetHousingDisRptParaDelegate(this.SetHousingDisRptPara);
            formRptPara.SetGetHousingStandRptDelegate(this.SetHousingStandRpt);

            this.BtnReport.Enabled = false;

            formRptPara.ShowDialog();
        }

        private void BtnReport_Click(object sender, EventArgs e)
        {
            this.BtnProc.Enabled = false;
            this.BtnReport.Enabled = false;

            DataTable dt = (DataTable)this.dataGridView.DataSource;
            ResetProgressBar(dt.Rows.Count);

            CtrlProgressBar(false);

            SaveFileDialog saveFileDialog = new SaveFileDialog();
            //saveFileDialog.Filter = "Excel files|*.xlsx";
            saveFileDialog.Filter = "Excel files|*.xls";
            saveFileDialog.FilterIndex = 0;
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.CreatePrompt = true;
            saveFileDialog.Title = "导出文件保存路径";
            saveFileDialog.ShowDialog();
            string path = saveFileDialog.FileName;

            if (path != null && path.Length > 0)
            {
                ExcelCreator excelCreator = new ExcelCreator(path, this.UpdateProgressBar);
                string title = DataDictionary.Instance().GetRptTitle(this.rptPersonType, this.rptPersonGrade);

                //预处理 DataGridView的 “任现职级副职时间” 的报表显示名称

                if (this.rptPersonType == PersonTypeEnum.ArmMan)
                {
                    string colName = DataDictionary.Instance().PersonTableFieldName(PersonColConsts.CUR_RANK_BEFORE_TIME);

                    string colTitle;

                    switch (this.rptPersonGrade)
                    {
                        case ArmmanGradeEnum.Army:
                            colTitle = "享受副军待遇时间";
                            break;

                        case ArmmanGradeEnum.Division:
                            colTitle = "享受副师待遇时间";
                            break;

                        case ArmmanGradeEnum.Regiment:
                            colTitle = "享受副团待遇时间";
                            break;

                        case ArmmanGradeEnum.Battalion:
                            colTitle = "享受副营待遇时间";
                            break;

                        default:
                            colTitle = "任现职级副职时间";
                            break;
                    }

                    this.dataGridView.Columns[colName].HeaderText = colTitle;
                }

                excelCreator.ExportTOExcel(this.rptPersonType, title, this.dataGridView);
            }

            CtrlProgressBar(true);

            this.BtnProc.Enabled = true;
            this.BtnReport.Enabled = true;
        }

        private void BtnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }


        //军人副职时间晚于分房时间的人，无法分房，需要修改人员信息
        private void buttonBeforeTimePeople_Click(object sender, EventArgs e)
        {
            PersonTypeEnum type = PersonTypeEnum.ArmMan;
            DGVDisplay(type, false);
            string sqlBeforePeople = "select * from person where  curRankBeforeTime > '" + HousingDisDeadline.Instance().Deadline().Year +"-"+HousingDisDeadline.Instance().Deadline().Month +"-"+HousingDisDeadline.Instance().Deadline().Day +"' and type ='1'";
            DataTable dt = DBProc.Instance().ReadData(sqlBeforePeople).Tables[0];
            this.dataGridView.DataSource = dt;

        }

        //*********************************Radio按钮处理代码**********************************************//
        private void radioBtnPerArmyMan_Click(object sender, EventArgs e)
        {
            ReadDataOnRadioClick();
        }

        private void radioBtnPerStaff_Click(object sender, EventArgs e)
        {
            ReadDataOnRadioClick();
        }

        private void radioBtnPerSeniorNCO_Click(object sender, EventArgs e)
        {
            ReadDataOnRadioClick();
        }

        private void radioBtnPerWorker_Click(object sender, EventArgs e)
        {
            ReadDataOnRadioClick();
        }

        private void radioBtnPerRetirement_Click(object sender, EventArgs e)
        {
            ReadDataOnRadioClick();
        }

        private void radioBtnPerOthers_Click(object sender, EventArgs e)
        {
            ReadDataOnRadioClick();
        }

        private void dataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            this.dataGridView.ReadOnly = false;

            int rowIndex = e.RowIndex;
            int colIndex = e.ColumnIndex;

            if (rowIndex < 0 || colIndex < 0)
                return;

            DataGridViewRow dr = this.dataGridView.Rows[rowIndex];
            string colName = this.dataGridView.Columns[colIndex].Name;

            bool check;
            int personID = 0;

            try
            {
                //不是“选房资格”的item无效
                if (colName.Equals(DataDictionary.Instance().PersonTableFieldName(PersonColConsts.HOUSING_ELIGIBLE)))
                {
                    check = Convert.ToBoolean(dataGridView.Rows[rowIndex].Cells[colIndex].EditedFormattedValue);
                    personID = Convert.ToInt16(dataGridView.Rows[rowIndex].Cells[DataDictionary.Instance().PersonTableFieldName(PersonColConsts.ID)].EditedFormattedValue);

                    UpdatePersonHousingEligible(personID, check ? 1 : 0);
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "设置人员选房资格出错");
            }
        }
        
        private void ForbidSortColumn(DataGridView dgv)
        {
            for (int i = 0; i < dgv.Columns.Count; i++)
            {
                dgv.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
            }
        }
        
        private void UpdatePersonHousingEligible(int id, int housingEligible)
        {
            StringBuilder sql = new StringBuilder("Update person set housingEligible ='");
            sql.Append(housingEligible.ToString());
            sql.Append("' where idperson ='");
            sql.Append(id.ToString());
            sql.Append("'");

            DBProc.Instance().Excute(sql.ToString());
        }
        
        void ReadDataOnRadioClick()
        {
            PersonTypeEnum curPersonType = GetPersonType();

            if (this.personType != curPersonType)
            {
                this.personType = curPersonType;

                ReadData(this.personType);
            }
        }
        
        /****************************进度条显示***********************************/
        void CtrlProgressBar(bool procCompleted)
        {
            this.panelProgressBar.Visible = !procCompleted;
        }

        void ResetProgressBar(int max)
        {
            this.progressBarProc.Value = 0;
            this.progressBarProc.Maximum = max;
        }

        void UpdateProgressBar(int value)
        {
            this.progressBarProc.Value = value;
        }

        public delegate void UpdateProgressBarDelegate(int value);

        #endregion

        #region 报表选择窗口的回调函数
        void SetHousingDisRptPara(PersonTypeEnum type, ArmmanGradeEnum rank)
        {
            this.dataGridView.DataSource = null;

            ForbidSortColumn(this.dataGridView);

            DGVDisplay(type, true);

            switch (type)
            {
                case PersonTypeEnum.ArmMan:
                    this.radioBtnPerArmyMan.Checked = true;
                    break;
                case PersonTypeEnum.Staff:
                    this.radioBtnPerStaff.Checked = true;
                    break;
                case PersonTypeEnum.Worker:
                    this.radioBtnPerWorker.Checked = true;
                    break;
                case PersonTypeEnum.NCO:
                    this.radioBtnPerSeniorNCO.Checked = true;
                    break;
            }

            HousingDisProcProxy procProxy = new HousingDisProcProxy(type, rank, this.BindData);
            Thread procThread = new Thread(procProxy.Proc);
            procThread.Start();

            this.rptPersonType = type;
            this.rptPersonGrade = rank;
        }

        private PersonTypeEnum rptPersonType;
        private ArmmanGradeEnum rptPersonGrade;

        private delegate void BindDataDelegate(DataTable dt);
        void BindData(DataTable dt)
        {
            if (this.dataGridView.InvokeRequired)
            {
                BindDataDelegate bindDataFunc = new BindDataDelegate(this.BindData);
                this.Invoke(bindDataFunc, new object[] { dt });
            }
            else
            {
                this.dataGridView.DataSource = dt;

                //报表按钮激活
                this.BtnReport.Enabled = true;
            }
        }

        class HousingDisProcProxy
        {
            public HousingDisProcProxy(PersonTypeEnum personType, ArmmanGradeEnum rank, BindDataDelegate bindDataFunc)
            {
                this.personType = personType;
                this.rank = rank;
                this.bindDataFunc = bindDataFunc;
            }

            public void Proc()
            {
                HousingDisProc proc = new HousingDisProc();

                DateTime deadline = HousingDisDeadline.Instance().Deadline();
                DataTable dt = proc.Proc(personType, deadline, rank);

                bindDataFunc(dt);
            }

           
            PersonTypeEnum personType;
            ArmmanGradeEnum rank;

            BindDataDelegate bindDataFunc;
        }


        //是否达标
        void SetHousingStandRpt(bool upToStand)
        {
            SpaceStandardProc proc = new SpaceStandardProc();
            this.dataGridView.DataSource = proc.Proc(upToStand);

            this.BtnReport.Enabled = true;
        }

        #endregion

        #region DGV显示控制

        void DGVDisplay(PersonTypeEnum type, bool sorted)
        {
            string[] titles;

            if (sorted)
                titles = DataDictionary.Instance().FormHousingDisDGVSortedDisplayedCols(type);
            else
                titles = DataDictionary.Instance().FormHousingDisDGVUnsortedDisplayedCols(type);


            for (int i = 0; i < this.dataGridView.Columns.Count; i++ )
            {
                DataGridViewColumn dgvc = this.dataGridView.Columns[i];

                if (titles.Contains(dgvc.Name))
                    dgvc.Visible = true;
                else
                    dgvc.Visible = false;
            }
        }

        #endregion

        #region 无效日期格式化
        private static string[] timeTypeCols = { DataDictionary.Instance().PersonTableFieldName(PersonColConsts.ADMIN_DUTY_TIME), DataDictionary.Instance().PersonTableFieldName(PersonColConsts.TECH_RANK_TIME), 
                                                    DataDictionary.Instance().PersonTableFieldName(PersonColConsts.TECH_TITLE_TIME), DataDictionary.Instance().PersonTableFieldName(PersonColConsts.CUR_RANK_BEFORE_TIME), 
                                                    DataDictionary.Instance().PersonTableFieldName(PersonColConsts.WORK_TIME),  DataDictionary.Instance().PersonTableFieldName(PersonColConsts.SCHOOL_TIME),
                                                    DataDictionary.Instance().PersonTableFieldName(PersonColConsts.SIGNUP_TIME), DataDictionary.Instance().PersonTableFieldName(PersonColConsts.RETIREMENT_TIME) };
        #endregion

        #region 控件初始化
        private void InitDGV()
        {
            DGVInit.Init(ref this.dataGridView, DataDictionary.Instance().GetDGVConf(DataDictionary.Instance().dgvNames[0]));
        }
        #endregion

        PersonTypeEnum personType;

    }
}
